package fun.shuofeng.juc.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.*;

public class CompletableFutureDemo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // test01();
        // test02();
        test03();
    }

    private static void test03() {
        CompletableFuture.supplyAsync(() -> "abc")
                .thenApply(s -> {
                    return "bbb";
                })
                .whenComplete((s, throwable) -> {
                    System.out.println("whenComplete " + s);
                    System.out.println("throwable " + throwable);
                })
                .handle((s, throwable) -> {
                    System.out.println("handle " + s);
                    System.out.println("throwable " + throwable);
                    // int i = 1 / 0;
                    return null;
                })
                .exceptionally(throwable -> {
                    System.out.println("exceptionally " + throwable);
                    return throwable;
                });
    }

    private static void test02() throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(() -> "null")
                .thenRun(() -> {
                    System.out.println("thenRun");
                });
        CompletableFuture.supplyAsync(() -> "supplyAsync")
                .thenAccept(s -> {
                    System.out.println("thenAccept " + s);
                });
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "supplyAsync")
                .thenApply(s -> {
                    System.out.println("thenAccept " + s);
                    return "thenAccept " + s;
                });
        System.out.println(completableFuture.get());
    }

    private static void test01() throws InterruptedException, ExecutionException {
        // 通过new关键字创建
        CompletableFuture<String> completableFuture = new CompletableFuture<>();
        completableFuture.complete("hello");
        System.out.println(completableFuture.get());
    }
}
